package com.mitgroup.dmrvs.view;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.mitgroup.dmrvs.R;
import com.mitgroup.dmrvs.service.VersionCheckService;
import com.mitgroup.dmrvs.utils.AppManager;
import com.mitgroup.dmrvs.utils.PermissionsChecker;
import com.mitgroup.dmrvs.utils.Utils;
import com.mitgroup.dmrvs.webservice.WSClient;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.PreferencesUtils;

public class LoginActivity extends AppCompatActivity {
    private static final int REQUEST_CODE = 0; // 请求码
    private boolean isRequireCheck; // 是否需要系统权限检测 //危险权限（运行时权限）
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA
    };
    private PermissionsChecker mPermissionsChecker;//检查权限
    private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限返回码
    private static final String PACKAGE_URL_SCHEME = "package:";
    private static final int MSG_LOGIN = 1;
    private static final String BUNDLE_LOGIN_FAIL = "login_fail";
    private static final String BUNDLE_LOCAL_ERROR = "local_error";
    private static final String BUNDLE_LOGIN_JUMP = "login_jump";
    private long exitTime = 0;
    private String userName;
    private String password;
    /**handler对象*/
    private Handler handler;
    private ProgressDialog progressDialog;
    @BindView(R.id.userName_et)
    public EditText etUserName;
    @BindView( R.id.password_et)
    public EditText etPassword;
    @BindView(R.id.login_btn)
    public Button btnLogin;
    @OnClick(R.id.login_btn)
    public void onLogin(View view) {
        userName=etUserName.getText().toString();
        password=etPassword.getText().toString();

        if (userName == null ||"".equals(userName))
        {
            Toast.makeText(this, "用户名不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else if(password == null ||"".equals(password))
        {
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        else
        {
            if(Utils.isNetworkAvailable(LoginActivity.this)==false)
            {
                Toast.makeText(this, "网络尚未连接，请连接网络！", Toast.LENGTH_SHORT).show();
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                return;
            }
            //String password1=MD5.encrypt(password);
            final String []key={"userName","password"};
            final String []value={userName,password};
            progressDialog = ProgressDialog.show(LoginActivity.this,
                    getResources().getString(R.string.notice), "正在登录...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    String rs = "";
                    Bundle bundle = new Bundle();
                    try {
                        rs = WSClient.soapGetInfo("userLogin",key,value);
                        if(rs!=null &&!"".equals(rs))
                        {

                            JSONTokener jsonTokener = new JSONTokener(rs);
                            JSONObject jsonObject = (JSONObject) jsonTokener
                                    .nextValue();
                            String status = jsonObject.getString("status");
                            String content = jsonObject.get("content").toString();
                            if("1".equals(status))
                            {
                                JSONObject jsonObject2 = jsonObject
                                        .getJSONObject("content");
                                String userId = jsonObject2.getString("userId");
                                String province = jsonObject2.getString("province");
                                String userType = jsonObject2.getString("userType");
                                String relUserId=jsonObject2.getString("relUserId");
                                String repairShopId=jsonObject2.getString("repairShopId");
                                PreferencesUtils.putString(LoginActivity.this,"userId", userId);
                                PreferencesUtils.putString(LoginActivity.this,"userName", userName);
                                PreferencesUtils.putString(LoginActivity.this,"password", password);
                                PreferencesUtils.putString(LoginActivity.this,"userType", userType);
                                PreferencesUtils.putString(LoginActivity.this,"province", province);
                                PreferencesUtils.putString(LoginActivity.this,"relUserId", relUserId);
                                PreferencesUtils.putString(LoginActivity.this,"repairShopId", repairShopId);
                                bundle.putString(BUNDLE_LOGIN_JUMP, "登录成功！");
                            }
                            else {

                                bundle.putString(BUNDLE_LOGIN_FAIL, "登录失败，用户名或密码错误！");
                            }
                        }
                        else
                        {
                            bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                        }

                    }
                    catch (Exception e) {
                        System.out.print(e.getMessage());
                        bundle.putString(BUNDLE_LOCAL_ERROR, "访问服务器失败！");
                    }
                    Message msg = myHandler.obtainMessage();
                    msg.what = MSG_LOGIN;
                    msg.setData(bundle);
                    myHandler.sendMessage(msg);
                }
            }).start();
        }

    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case MSG_LOGIN:
                    String key = msg.getData().keySet().iterator().next();
                    if (BUNDLE_LOGIN_FAIL.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(LoginActivity.this, msg.getData().getString(BUNDLE_LOGIN_FAIL), Toast.LENGTH_SHORT).show();
                    }
                    else if (msg.getData().keySet().contains(BUNDLE_LOGIN_JUMP)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(LoginActivity.this, msg.getData().getString(BUNDLE_LOGIN_JUMP), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LoginActivity.this,
                                MyMainActivity.class);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    }
                    else if (BUNDLE_LOCAL_ERROR.equals(key)) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast.makeText(LoginActivity.this, "服务器连接失败！请重试！", Toast.LENGTH_SHORT).show();
                    }
                    break;

                default:
                    break;
            }
            removeMessages(msg.what);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        mPermissionsChecker = new PermissionsChecker(this);
        isRequireCheck = true;
        initView();
    }
    @Override
    protected void onResume() {
        super.onResume();

        if (isRequireCheck) {
            //权限没有授权，进入授权界面
            if (mPermissionsChecker.judgePermissions(PERMISSIONS)) {
                ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST_CODE);
            }
        } else {
            isRequireCheck = true;
        }
    }
    private void initView() {
        AppManager.getAppManager().addActivity(this);
        //检查版本更新
         checkVersion();
        //创建本地文件夹
        createFolder();
        String userId= PreferencesUtils.getString(LoginActivity.this,"userId");
        if(userId!=null && !"".equals(userId) && !"null".equals(userId))
        {
            Intent intent = new Intent();
            intent.setClass(LoginActivity.this, MyMainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //注意本行的FLAG设置
            startActivity(intent);
            this.finish();
            return;
        }
        else
        {
            userName=PreferencesUtils.getString(LoginActivity.this,"userName");
            password=PreferencesUtils.getString(LoginActivity.this,"password");
            if(userName!=null &&!"".equals(userName))
            {
                etUserName.setText(userName);
            }
            if(password!=null && !"".equals(password))
            {
                etPassword.setText(password);
            }

        }
    }
    /**
     * 创建一个文件夹
     */
    private void createFolder(){
        File file = new File(Environment.getExternalStorageDirectory()+"/dmrvs/");
        if (!file.exists()) {
            file.mkdir();
        }
        file = new File(Environment.getExternalStorageDirectory()+"/doc/");
        if (!file.exists()) {
            file.mkdir();
        }
    }
    private void checkVersion(){
        //http://www.welion.net/dmrvsWS/apk/version.txt
        VersionParams.Builder builder = new VersionParams.Builder()
                .setRequestUrl("http://www.welion.net/dmrvsWS/apk/version.txt")
                .setService(VersionCheckService.class);
        stopService(new Intent(this, VersionCheckService.class));
        builder.setPauseRequestTime(10L);
        builder.setDownloadAPKPath("/storage/emulated/0/dmrvs/");
        //更新界面选择
        CustomVersionDialogActivity.customVersionDialogIndex = 2;
        //更改下载界面
        CustomVersionDialogActivity.isCustomDownloading = true;
        //强制更新
        CustomVersionDialogActivity.isForceUpdate = true;
        builder.setCustomDownloadActivityClass(CustomVersionDialogActivity.class);
        //强制重新下载
        builder.setForceRedownload(true);
        AllenChecker.startVersionCheck(this, builder.build());
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(LoginActivity.this,"再按一次退出", Toast.LENGTH_LONG).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grantResults)) {
            isRequireCheck = true;
        }
        else {
            isRequireCheck = false; showPermissionDialog();
        }
    }
    // 含有全部的权限
    private boolean hasAllPermissionsGranted( int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        } return true;
    }
    /**
     * 提示对话框
     */
    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                LoginActivity.this); builder.setTitle("帮助");
        builder.setMessage("当前应用缺少必要权限。请点击\"设置\"-打开所需权限。");
        // 拒绝, 退出应用
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //setResult(PERMISSIONS_DENIED);
                        LoginActivity.this.finish();
                    }
                }
        );
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        }); builder.setCancelable(false); builder.show();
    } // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }
}
